<?php
namespace App\Repos;

use App\Models\Cart;
use App\Models\Product;
use DB;
class CartRepo
{
	public static function  getPages($where=[])
	{	   
	  	$list = DB::table('carts as a')
	  				->join('products as b','a.product_id','=','b.id')
	  				->select('a.id','a.product_id','a.product_num','a.product_price','a.product_name','a.product_thumb','a.sub_total','b.market_price',DB::raw('a.product_num*(b.market_price-a.product_price) as sub_saved_total'))
			  		->where($where)
			  		->get();
			  		

	  	return $list;     
	}

	public static function create($data)
	{
		// 如果已经存在此商品那么增加商品数量
		$where = array_only($data, ['user_id', 'product_id']);
		$flag = Cart::where($where)->first();
		if($flag) {
			$flag->product_num += $data['product_num']; 
			$flag->sub_total = $flag->product_num*$flag->product_price;
			$flag->save();
		} else {
			$product = Product::find($data['product_id']);
			$data['product_name']  = $product->name;
			$data['product_thumb'] = $product->thumb;
			$data['sub_total'] = $data['product_num']*$product->price;
			$flag = Cart::create($data);
		} 
		return $flag;
		
	}

	/**
	 * 购物车减少
	 */
	public static function decrease($data)
	{
		$where['user_id']    = $data['user_id'];
		$where['product_id'] = $data['product_id'];
		$cart = Cart::where($where)->first();
		// 购物车必须保留一个
		if($cart->product_num<2) {
			return $cart;			
		} 
		$cart->product_num = $cart->product_num-1;		
		$cart->save();
		return $cart;
	}

	/**
	 * 购物车增加数量
	 */
	public static function increase($data)
	{
		$where['user_id']    = $data['user_id'];
		$where['product_id'] = $data['product_id'];
		$cart = Cart::where($where)->first();
		
		$cart->product_num = $cart->product_num+1;		
		$cart->save();
		return $cart;
	}

	/**
	 * 删除购物车
	 */
	public static function delete($data)
	{
		$rs = Cart::destroy($data['cart_id']);
		if($rs) {
			return true;
		} 
		return false;
	}

	/**
	 * 释放购物车
	 */
	public static function release($where)
	{
		return Cart::where($where)->delete();
	}


	public static function get($ids=[])
	{
		return Cart::whereIn('id',$ids)->get();
	}

	public static function find($where)
	{
		return Cart::where($where)->first();
	}

	
	
	

	
	
	
}